package com.zpwq.task;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zpwq.bean.Task;
import com.zpwq.service.TaskService;

@Component
public class SendTask {
	private static ConcurrentLinkedQueue<Task> queue = new ConcurrentLinkedQueue<Task>();
	private static AtomicInteger num = new AtomicInteger();
	private static final int MAX = 5 ;
	
	@Resource
	private TaskService taskService;
	
	public static void addSendTask(Task task){
		queue.add(task);
	}
	@Scheduled(fixedRate = 1000) //间隔启动
	public void send(){
		try{
			if(num.incrementAndGet()<= MAX){
				synchronized(queue){
					while(!queue.isEmpty()){
						Task task = queue.poll();
						taskService.send(task);
					}
				}
			}
		}finally{
			num.decrementAndGet();
		}
	}
	
	@Scheduled(fixedDelay = 1000) //完成后启动
	public void work(){
		taskService.workAll();
	}
	
	public static void main(String[] args) {
		System.out.println(num.get());
		System.out.println(num.incrementAndGet());
		System.out.println(num.get());
		System.out.println(num.decrementAndGet());
		System.out.println(num.decrementAndGet());
		System.out.println(num.incrementAndGet());
	}
	
	
	
	
}
